package com.stormrage.edu.ctrl.learn;

import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.stormrage.edu.serv.adm.AdmAcctServ;
import com.stormrage.edu.serv.learn.LeaBunchServ;
import com.stormrage.edu.serv.learn.LeaStudentServ;
import com.stormrage.entity.adm.AdmRes;
import com.stormrage.entity.learn.req.LeaBunchReq;
import com.stormrage.entity.learn.req.LeaStudentReq;
import com.stormrage.entity.rep.ErrorRep;
import com.stormrage.entity.rep.JsonRep;
import com.stormrage.entity.rep.ListRep;
import com.stormrage.entity.shiro.ShiroAcct;
import com.stormrage.shiro.bind.CurrentUser;
import com.stormragetech.core.ctrl.BaseCtrl;
import com.stormragetech.core.entity.Page;

/**
 * @Title: LeaTermCtrl.java
 * @Package com.stormrage.edu.ctrl.learn
 * @Description: 学期 Controller
 * @author www.stormragetech.com
 * @date 2016年4月13日
 * @version V1.0
 */
@Controller
@RequestMapping("/bunch")
public class LeaBunchCtrl extends BaseCtrl {

	private static final Logger logger = LoggerFactory.getLogger(LeaTermCtrl.class);

	@Value("#{constants['html.title']}")
	private String htmlTitle;

	@Autowired
	private AdmAcctServ admAcctServ;

	@Autowired
	private LeaBunchServ leaBunchServ;

	@Autowired
	private LeaStudentServ leaStudentServ;

	@RequiresPermissions("bunch:view")
	@RequestMapping(value = "/{id}/list")
	public String list(@CurrentUser ShiroAcct curr, LeaBunchReq req, Model model) {

		logger.debug(" 【 Controller 】-【 LeaBunchCtrl 】-【 List 】-【 POST 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			String search = JSON.toJSONString(req);

			if (null != search && search.length() > 0)
				model.addAttribute("search", search);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 LeaBunchCtrl 】-【 List 】-【 GET 】- 结束运行 ");
		return "lea/bunch/list";
	}

	@RequiresPermissions("bunch:view")
	@RequestMapping(value = "/{id}/ajax", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String ajax(@RequestParam(value = "draw", required = true) Integer draw,
			@RequestParam(value = "start", required = true) Integer start,
			@RequestParam(value = "length", required = true) Integer length, @PathVariable("id") Integer id,
			LeaBunchReq req) {

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 Ajax 】-【 POST 】-【 STARTED 】");

		String json = null;

		try {

			// ------------------ 获取初始化模块的状态 ------------------
			Page page = Page.instance(start, length, 1);
			req = LeaBunchReq.instance(req, id, 0, page);
			draw += 1;

			logger.debug(" 分页信息为 " + page.toString());

			ListRep entity = leaBunchServ.queryListForLearn(req);

			JsonRep rep = JsonRep.instance(entity.getCount(), draw, entity.getList());
			json = JSON.toJSONString(rep);

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 返回的json为 " + json);
		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 Ajax 】-【 POST 】-【 COMPLETED 】");
		return json;

	}
	
	

	@RequiresPermissions("bunch:view")
	@RequestMapping(value = "/{cid}/{id}/del")
	public String delete(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id,  RedirectAttributes redirect) {
		
		logger.debug(" 【 Controller 】-【 LeaBunchCtrl 】-【 delete 】-【 GET 】- 开始运行 ");
		
		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------
			leaBunchServ.delete(id);
			errMsg = "提示信息：删除班级成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：删除班级失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/bunch/{cid}/list";
		}

		logger.debug(" 【 Controller 】-【 LeaBunchCtrl 】-【 Delete 】-【 GET 】- 结束运行 ");
		return "redirect:/bunch/{cid}/list";

	}

	@RequiresPermissions("bunch:view")
	@RequestMapping(value = "/{cid}/{id}/study")
	public String study(@CurrentUser ShiroAcct curr, LeaStudentReq req, Model model) {

		logger.debug(" 【 Controller 】-【 LeaBunchCtrl 】-【 Study 】-【 POST 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			String search = JSON.toJSONString(req);

			logger.debug(" 查询条件req变为search为 " + search);

			if (null != search && search.length() > 0)
				model.addAttribute("search", search);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 LeaBunchCtrl 】-【 Study 】-【 GET 】- 结束运行 ");
		return "lea/stu/study";
	}

	@RequiresPermissions("bunch:view")
	@RequestMapping(value = "/{cid}/{id}/sajax", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String sajax(@RequestParam(value = "draw", required = true) Integer draw,
			@RequestParam(value = "start", required = true) Integer start,
			@RequestParam(value = "length", required = true) Integer length, @PathVariable("id") Integer id,
			LeaStudentReq req) {

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 SAjax 】-【 POST 】-【 STARTED 】");

		String json = null;

		try {

			// ------------------ 获取初始化模块的状态 ------------------
			Page page = Page.instance(start, length, 1);
			req = LeaStudentReq.instance(req, id, 0, page);
			draw += 1;

			logger.debug(" 分页信息为 " + page.toString());

			ListRep entity = leaStudentServ.queryListForStudy(req);

			logger.debug(" 返回信息为 " + entity.toString());

			JsonRep rep = JsonRep.instance(entity.getCount(), draw, entity.getList());
			json = JSON.toJSONString(rep);

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 返回的json为 " + json);
		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 SAjax 】-【 POST 】-【 COMPLETED 】");
		return json;

	}

	@RequiresPermissions("bunch:view")
	@RequestMapping(value = "/{cid}/{id}/score")
	public String score(@CurrentUser ShiroAcct curr, LeaStudentReq req, Model model) {

		logger.debug(" 【 Controller 】-【 LeaBunchCtrl 】-【 Score 】-【 POST 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			String search = JSON.toJSONString(req);

			logger.debug(" 查询条件req变为search为 " + search);

			if (null != search && search.length() > 0)
				model.addAttribute("search", search);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 LeaBunchCtrl 】-【 Score 】-【 GET 】- 结束运行 ");
		return "lea/stu/score";
	}

	@RequiresPermissions("bunch:view")
	@RequestMapping(value = "/{cid}/{id}/cajax", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String cajax(@RequestParam(value = "draw", required = true) Integer draw,
			@RequestParam(value = "start", required = true) Integer start,
			@RequestParam(value = "length", required = true) Integer length, @PathVariable("id") Integer id,
			LeaStudentReq req) {

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 CAjax 】-【 POST 】-【 STARTED 】");

		String json = null;

		try {

			// ------------------ 获取初始化模块的状态 ------------------
			Page page = Page.instance(start, length, 1);
			req = LeaStudentReq.instance(req, id, 0, page);
			draw += 1;

			logger.debug(" 分页信息为 " + page.toString());

			ListRep entity = leaStudentServ.queryListForScore(req);

			JsonRep rep = JsonRep.instance(entity.getCount(), draw, entity.getList());
			json = JSON.toJSONString(rep);

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 返回的json为 " + json);
		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 CAjax 】-【 POST 】-【 COMPLETED 】");
		return json;

	}

	@RequestMapping(value = "/{aid}/{id}/oper", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String oper(@PathVariable("id") Integer id, HttpServletResponse response) {

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 oper 】-【 POST 】-【 STARTED 】");

		try {

			response.setContentType("application/x-msdownload;charset=UTF-8");
			// response.setContentType("application/binary;charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=operscore.xls");
			OutputStream os = response.getOutputStream();
			Workbook workbook = leaBunchServ.queryOperExcel(id);
			workbook.write(os);
			os.flush();
			os.close();

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 oper 】-【 POST 】-【 COMPLETED 】");
		return null;

	}

	@RequestMapping(value = "/{aid}/{id}/usua", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String usua(@PathVariable("id") Integer id, HttpServletResponse response) {

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 usua 】-【 POST 】-【 STARTED 】");

		try {

			response.setContentType("application/x-msdownload;charset=UTF-8");
			// response.setContentType("application/binary;charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=usuascore.xls");
			OutputStream os = response.getOutputStream();
			Workbook workbook = leaBunchServ.queryUsuaExcel(id);
			workbook.write(os);
			os.flush();
			os.close();

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 usua 】-【 POST 】-【 COMPLETED 】");
		return null;

	}

	@RequestMapping(value = "/{aid}/{id}/upusua", method = RequestMethod.GET)
	public String upusua(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】- 【 LeaApplyCtrl 】- 【 upusua 】-【 GET 】- 开始运行  ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ 返回信息赋值 ------------------
			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("id", id);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】- 【 LeaApplyCtrl 】- 【 upusua 】-【 GET 】- 结束运行  ");
		return "lea/bunch/usua/upload";

	}

	@RequestMapping(value = "/{aid}/{id}/upusua", method = RequestMethod.POST)
	public String upusua(@CurrentUser ShiroAcct curr, @RequestParam(value = "file", required = true) MultipartFile file,
			RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】- 【 LeaApplyCtrl 】- 【 upusua 】-【 POST 】- 开始运行  ");

		ErrorRep err = null;
		String errMsg = "";

		if (null == file || file.isEmpty()) {
			errMsg = "提示信息：上传平时成绩失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/bunch/{aid}/{id}/upusua";
		}

		try {

			// ------------------ Ctrl操作 ------------------

			leaBunchServ.uploadUsua(file);

			errMsg = "提示信息：上传平时成绩成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：上传平时成绩失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/bunch/{aid}/{id}/upusua";
		}

		logger.debug(" 【 Controller 】-【 LeaApplyCtrl 】-【 upusua 】-【 POST 】- 结束运行 ");
		return "redirect:/bunch/{aid}/{id}/score";

	}

	@RequestMapping(value = "/{aid}/{id}/upoper", method = RequestMethod.GET)
	public String upoper(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】- 【 LeaApplyCtrl 】- 【 upoper 】-【 GET 】- 开始运行  ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ 返回信息赋值 ------------------
			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("id", id);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】- 【 LeaApplyCtrl 】- 【 upoper 】-【 GET 】- 结束运行  ");
		return "lea/bunch/oper/upload";

	}

	@RequestMapping(value = "/{aid}/{id}/upoper", method = RequestMethod.POST)
	public String upoper(@CurrentUser ShiroAcct curr, @RequestParam(value = "file", required = true) MultipartFile file,
			RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】- 【 LeaApplyCtrl 】- 【 upoper 】-【 POST 】- 开始运行  ");

		ErrorRep err = null;
		String errMsg = "";

		if (null == file || file.isEmpty()) {
			errMsg = "提示信息：上传实操成绩失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/bunch/{aid}/{id}/upusua";
		}

		try {

			// ------------------ Ctrl操作 ------------------

			leaBunchServ.uploadOper(file);

			errMsg = "提示信息：上传实操成绩成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：上传实操成绩失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/bunch/{aid}/{id}/upusua";
		}

		logger.debug(" 【 Controller 】-【 LeaApplyCtrl 】-【 upoper 】-【 POST 】- 结束运行 ");
		return "redirect:/bunch/{aid}/{id}/score";

	}

}
